<template>
    <div class="publishArticle-wrapper" ref="publishArticleWrapper">

        <!--工具栏-->
        <Toolbar
            ref="toolbar"
            class="toolbar"
            :mode="mode"
            :defaultConfig="toolbarConfig"
            :editor="editorRef"
        />

        <!--编辑器-->
        <div class="content" ref="content">
            <div class="editor-container">
                <div class="title-container">
                    <input v-model="formData.name" placeholder="标题...">
                </div>
                
                <Editor
                    class="editor"
                    :mode="mode"
                    :defaultConfig="editorConfig"
                    v-model="formData.content"
                    @onCreated="handleCreated"
                />
            </div>
        </div>

        <!--预览发布按钮-->
        <div class="bottom-btns">
            <el-button size="large">预览</el-button>
            <el-button 
                type="primary"
                size="large"
                @click="submit"
            >
                {{ isShowForm ? '提交' : formData.id ? '修改' : '发布' }}
            </el-button>
        </div>

        <!--发布表单-->
        <div 
            class="bottom-form" 
            ref="bottomForm"
            :style="{ bottom: isShowForm ? '60px' : '-245px' }"
        >
            <el-form 
                class="form" 
                :rules="rules"
                ref="formRef"
                :model="formData"
            >
                <el-button 
                    type="danger" 
                    size="small" 
                    circle 
                    style="position: absolute; right: 5px; top: 5px;font-size: 16px;"
                    @click="isShowForm = false"
                >
                    <el-icon><Close /></el-icon>
                </el-button>

                <el-form-item label="name" prop="name">
                    <el-input 
                        v-model="formData.name" 
                        disabled
                        style="width: 320px"
                    />
                </el-form-item>

                <el-form-item label="category" prop="category_id">
                    <el-select
                        v-model="formData.category_id"
                        placeholder="分类"
                        style="width: 240px"
                    >
                        <el-option 
                            v-for="category in categories"
                            :key="category.id"
                            :label="category.name"
                            :value="category.id"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="cover_imgs" prop="cover_imgs">
                    <el-upload 
                        action="/api/cover_img"
                        list-type="picture-card"
                        :limit="3"
                        v-model:file-list="fileList"
                    >
                        <el-icon><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

import { shallowRef } from 'vue'
import { Close, Plus } from '@element-plus/icons-vue'
import { getCategoryByPage } from '@/api/category.js'
import { setArticle, getArticleById } from '@/api/article.js'

export default {
    name: 'publishArticle',
    components: {
        Editor,
        Toolbar,
        Close,
        Plus
    },
    data () {
        return {
            //富文本配置项
            mode: 'default',
            toolbarConfig: {
                excludeKeys: [
                    'fullScreen'
                ]
            },
            editorConfig: { 
                scroll: false,
                placeholder: '请输入内容...',
                MENU_CONF: {
                    uploadImage: {
                        server: '/api/article_img',
                    },
                    uploadVideo: {
                        server: '/api/article_video',
                    }
                }
            },

            //是否展示表单
            isShowForm: false,
            //文章分类
            categories: null,
            
            //提交方式
            method: 'POST',
            //表单数据
            formData: {
                id: null,
                name: null,
                content: null,
                category_id: null,
                cover_imgs: [],
                article_imgs: [],
                article_videos: []
            },
            //临时保存cover_imgs
            fileList: [],
            
            rules: {
                name:[
                    { required: true, message: '标题不能为空', trigger: 'blur' },
                    { max: 64, message: '最大长度为64', trigger: 'blur' },
                ],
                category_id: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                cover_imgs: [
                    { validator: this.validateCoverImgs, trigger: 'change' }
                ]
            }
        }
    },
    methods: {
        //自定义验证封面图
        validateCoverImgs (rule, value, callback) {
            if (value.length === 3) {
                callback()
            } else if (value.length === 1) {
                callback()
            } else if (value.length === 0) {
                callback()
            } else {
                callback(new Error('封面图只能是三张, 一张, 或无封面'))
            }
        },

        //提交formData
        submit () {
            if (!this.isShowForm) return this.isShowForm = true

            this.formData.cover_imgs.length = this.fileList.length
            this.$refs.formRef.validate(async (valid, fields) => {
                if (valid) {
                    //将cover_imgs, article_imgs, article_videos转换为我们后端所需要的格式
                    let cover_imgs = this.fileList.filter(img => img.response).map(img => img.response.data)
                    this.formData.cover_imgs = cover_imgs
                    this.formData.article_imgs = this.editorRef.getElemsByType('image').map(obj => obj.src)
                    this.formData.article_videos = this.editorRef.getElemsByType('video').map(obj => obj.src)

                    //提交请求
                    let result = await setArticle(this.formData, this.method)
                    if (result instanceof Error) return ElMessage.error(result.message)
                    ElMessage.success('发布文章成功')

                    //跳转页面
                    this.$router.replace('/workManage')
                }
            })
        },

        //获取所有文章分类
        async categoryByPage () {
            let result = await getCategoryByPage(1, 999)
            if (result instanceof Error) return ElMessage.error(result.message)

            this.categories = result
        },

        //给window添加resize事件确保浏览器窗口发生改变时的整体布局
        resize () {
            let publishArticleWrapper = this.$refs.publishArticleWrapper
            let toolbar = document.querySelector('.toolbar')
            let content = this.$refs.content

            publishArticleWrapper.style.height = `${ window.innerHeight - 65 }px`
            content.style.height = `${ window.innerHeight - 65 - 20 - 60 - toolbar.offsetHeight }px`
        }
    },

    //初始化
    mounted () {
        window.addEventListener('resize', this.resize)
        setTimeout(this.resize, 0)

        this.categoryByPage()

        //如何存在id当前操作为修改页面
        let id = this.$route.params.id
        if (id) {
            this.formData.id = id
            this.method = 'PUT'

            //根据id获取文章信息
            getArticleById(id)
            .then(article => {
                for (const key of Reflect.ownKeys(this.formData)) {
                    this.formData[key] = article[key]
                }

                //将cover_imgs转换为页面所需要的格式
                for (let i = 0; i < this.formData.cover_imgs.length; i++) {
                    this.fileList[i] = {
                        response: {
                            data: this.formData.cover_imgs[i]
                        },
                        url: this.formData.cover_imgs[i]
                    }
                }
            })
        }
    },
    unmounted () {
        window.removeEventListener('resize', this.resize)
    },

    //富文本编辑器一些设置必须在setup函数中配合shallowRef才能完成
    setup () {
        const editorRef = shallowRef()

        const handleCreated = (editor) => {
            editorRef.value = editor // 记录 editor 实例，重要！
        }

        return {
            editorRef,
            handleCreated
        }
    }
}
</script>

<style lang="less" scoped>
.publishArticle-wrapper{
    padding: 20px;
    position: relative;
    overflow: hidden;

    .toolbar{
        display: flex;
        justify-content: center;
        border-bottom: 1px solid #e8e8e8;
        border-top: 1px solid #e8e8e8;
    }

    .content {
        background-color: rgb(245, 245, 245);
        overflow-y: auto;
        position: relative;
        .editor-container {
            width: 850px;
            margin: 30px auto 60px auto;
            background-color: #fff;
            padding: 20px 50px 50px 50px;
            border: 1px solid #e8e8e8;
            box-shadow: 0 2px 10px rgb(0 0 0 / 12%);

            .title-container {
                padding: 20px 0;
                border-bottom: 1px solid #e8e8e8;

                input {
                    font-size: 30px;
                    border: 0;
                    outline: none;
                    width: 100%;
                    line-height: 1;
                }
            }

            .editor {
                min-height: 900px;
                margin-top: 20px;
            }
        }
    }

    .bottom-btns{
        height: 60px;
        box-sizing: border-box;
        border-top: 1px solid #d8d8d8;
        background-color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        z-index: 99;
    }

    .bottom-form{
        position: absolute;
        left: 20px;
        right: 20px;
        z-index: 9;
        background-color: #fff;
        transition: bottom ease 1.5s;
        display: flex;
        justify-content: center;
        border-top: 1px solid #e8e8e8;

        .form{
            width: 750px;
            height: 305px;
            padding-top: 20px;
            padding-right: 20px;
            position: relative;
        }
    }
}
</style>